<?php
class Shipping_Service_ShipPrice
{
     public static function add($row){
        $obj = new Shipping_Model_ShipPrice();
        return $obj->add($row);
	}

	public static function update($row,$value,$field='sp_id'){
        $obj = new Shipping_Model_ShipPrice();
        return $obj->update($row,$value,$field);
	}


	public static function delete($value,$field='sp_id'){
        $obj = new Shipping_Model_ShipPrice();
        return $obj->delete($value,$field);

	}


	public static function getByValue($value,$field='sp_id'){
        $obj = new Shipping_Model_ShipPrice();
        return $obj->getByValue($value,$field);
	}

    public static function getByCondition($condition,$type='*',$orderby="",$page=0,$pageSize=0){
        $obj = new Shipping_Model_ShipPrice();
        return $obj->getByCondition($condition,$type,$orderby,$page,$pageSize);
	}

    public static function getInfo($rowList) {

        foreach($rowList as $key =>$row){
            $warehouse=Warehouse_Service_Warehouse::getByfield('warehouse_id',$row['warehouse_id']);
            if(isset($warehouse[0]))
            {
                $rowList[$key]['warehouse_name'] = $warehouse[0]['warehouse_name'];
            }
        }
        return $rowList;
    }

    public static function validator($val) {
        $error = array();
        $validateArr = array();
        $validateArr[] = array('name' => '重量', 'value' => $val['sp_weight'], 'regex' => array('require', 'positive1'));
        $validateArr[] = array('name' => '价格', 'value' => $val['sp_cost'], 'regex' => array('require', 'positive1'));
		$validateArr[] = array('name' => '货币', 'value' => $val['currency_code'], 'regex' => array('require'));
        $validateArr[] = array('name' => '区域标签', 'value' => $val['area'], 'regex' => array('require', 'noCharacter'));

        $validateArr[] = array('name' => '运输方式', 'value' => $val['st_id'], 'regex' => array('require'));
        $validateArr[] = array('name' => '仓库', 'value' => $val['warehouse_id'], 'regex' => array('require'));
        $validateArr[] = array('name' => '计费类型', 'value' => $val['sp_calc_type'], 'regex' => array('require'));
        $error = Common_Service_Validator::formValidator($validateArr);

        if(!empty($val['area']) && !empty($val['st_id'])&& !empty($val['warehouse_id'])&& !empty($val['sp_weight'])){
            $condition = array(
//                 'sp_id' =>$val['sp_id'],
                'area' =>$val['area'],
                'st_id' =>$val['st_id'],
                'warehouse_id' =>$val['warehouse_id'],
                'sp_weight1' =>$val['sp_weight'],
            );
            $shipTypeList = self::getByCondition($condition);
            if(!empty($shipTypeList)){
                $error[] ='当前仓库，运输方式，重量，区域对应的价格已经存在';
            }
        }
        return $error;

    }


    public static function getCalcTypeList() {
        return array(
            'p' =>'取重量区间价格',
            'w' =>'按重量乘基本费用',
        );
    }
    
    /**
     * 读取上传文件
     * @param string $fileName
     * @return array
     */
    public static function readUploadFile($fileName,$filePath){
    	$columnMap = array(
    			"ProductNo" => "product_sku",
    			"ProductName" => "product_title",
    			"Category" => "Category",
    			"UOM" => "UOM",
    			"Length" => "product_length" ,
    			"Height" => "product_height",
    			"Width" => "product_width",
    			"Weight" => "product_weight" ,
    			"Declare Value" => "product_declared_value",
    			"Min Qty" => "Min_Qty",
    			"CustomerId" => "customer_id",
    	);
    	$pathinfo = pathinfo($fileName);
    	$fileData = array();
    	if($pathinfo["extension"] == "xls"){
    		$fileData = Product_Service_Upload::readEXCEL($filePath);
    	}elseif($pathinfo["extension"] == "csv"){
    		$fileData = Product_Service_Upload::readCSV($filePath);
    	}else{
    		return false;
    	}
    	foreach($fileData[0] as $key => $value){
    		if(isset($columnMap[$value])){
    			$fileData[0][$key] = $columnMap[$value];
    		}
    	}
    	$result = array();
    	foreach($fileData as $key => $value){
    		//将第一行value转成其他行的key
    		if ($key == 0){
    			continue;
    		}
    		foreach($value as $vKey => $vValue){
    			if($fileData[0][$vKey] == "") continue;
    			$result[$key][$fileData[0][$vKey]] = $vValue;
    		}
    	}
    	//		print_r($result);die();
    	return $result;
    }
    
    /**
     * 批量导入
     * @param string $fileName
     * @return array
     */
    public static function batchAddShipPrice($shipType,$row,$warehouseId=1){
    	
    	if(empty($row)||empty($shipType)){
    		return "数据异常";
    	}
    	$productSer = new Product_Service_Product();
    	$adapter = $productSer->getAdapter();
    	$adapter->beginTransaction();
    	try {    		
    		//删除仓库物流方式对应的运输价格纪录
    		$condition = array("st_code"=>$shipType,'warehouse_id'=>$warehouseId);
    		$ship_price_list = self::getByCondition($condition);
    		 
    		//     	print_r($row);
    		//     	print_r($ship_price_list);exit;
    		foreach($ship_price_list as $v){
    			self::delete($v['sp_id'],"sp_id");
    		}
    		
    		$shipTypeArr =  Shipping_Service_ShipType::getByValue($shipType,"st_code");
    		if(empty($shipTypeArr)){    			
    			$adapter->rollback();
    			return array('status'=>0,'msg'=>"物流方式异常，不存在 $shipType 物流方式");    	
    		}
    		$errlist = array();
    		foreach($row as $k=>$v){
    			$arr = array();
    			$arr['sp_weight'] = $v['sp_weight'];
    			$arr['sp_cost'] = $v['sp_price'];
    			$arr['currency_code'] = $v['currency_code'];
    			$arr['area'] = $v['zone'];
    			$arr['st_code'] = $v['ship_type'];
    			$arr['sp_calc_type'] = $v['fee_type'];
    			//     		$shipType =  Shipping_Service_ShipType::getByValue($v['ship_type'],"st_code");
    			$arr['st_id'] = $shipTypeArr['st_id'];
    			$arr['warehouse_id'] = $warehouseId;
    			//     		print_r($arr);exit;
    			$validat = self::validator($arr);
    			if(empty($validat)){    				
    				self::add($arr);
    			}else{
    				$arr['err'] = $validat;
    				$errlist[] = $arr;
    			}
    		}
    		$adapter->commit();
    		return array('status'=>1,'msg'=>"导入成功",'errlist'=>$errlist);
    			
    	}catch (Exception $e){
    		$adapter->rollback();
    		return array('status'=>0,'msg'=>$e->getMessage());
    	}
    	
    }
    
    
}